using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml.Serialization;

class Program
{
    static void Main(string[] args)
    {
        OrderService orderService = new OrderService();

        // 添加订单示例
        Customer customer = new Customer { Name = "张三" };
        Product product = new Product { Name = "商品A", Price = 100 };
        OrderDetail orderDetail = new OrderDetail { Product = product, Quantity = 2 };
        Order order = new Order { OrderId = "001", Customer = customer, Details = new List<OrderDetail> { orderDetail } };
        orderService.AddOrder(order);

        // 查询订单示例
        var orders = orderService.QueryOrders(o => o.Customer.Name == "张三");
        foreach (var o in orders)
        {
            Console.WriteLine(o);
        }

        // 修改订单示例
        try
        {
            orderService.UpdateOrder("001", new Order { OrderId = "001", Customer = customer, Details = new List<OrderDetail> { orderDetail, new OrderDetail { Product = new Product { Name = "商品B", Price = 200 }, Quantity = 1 } } });
        }
        catch (Exception e)
        {
            Console.WriteLine($"修改订单失败: {e.Message}");
        }

        // 删除订单示例
        try
        {
            orderService.DeleteOrder("001");
        }
        catch (Exception e)
        {
            Console.WriteLine($"删除订单失败: {e.Message}");
        }

        // 导出订单示例
        try
        {
            orderService.Export("orders.xml");
            Console.WriteLine("订单已成功导出到 orders.xml");
        }
        catch (Exception e)
        {
            Console.WriteLine($"导出订单失败: {e.Message}");
        }

        // 导入订单示例
        try
        {
            orderService.Import("orders.xml");
            Console.WriteLine("订单已成功从 orders.xml 导入");
        }
        catch (Exception e)
        {
            Console.WriteLine($"导入订单失败: {e.Message}");
        }

        Console.ReadLine();
    }
}

public class Customer
{
    public string Name { get; set; }

    public override string ToString()
    {
        return $"客户: {Name}";
    }
}

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public override string ToString()
    {
        return $"商品: {Name}, 单价: {Price}";
    }
}

public class OrderDetail
{
    public Product Product { get; set; }
    public int Quantity { get; set; }

    public override bool Equals(object obj)
    {
        if (obj is OrderDetail other)
        {
            return Product.Equals(other.Product) && Quantity == other.Quantity;
        }
        return false;
    }

    public override string ToString()
    {
        return $"{Product}, 数量: {Quantity}";
    }
}

public class Order
{
    public string OrderId { get; set; }
    public Customer Customer { get; set; }
    public List<OrderDetail> Details { get; set; } = new List<OrderDetail>();

    public decimal TotalAmount => Details.Sum(d => d.Product.Price * d.Quantity);

    public override bool Equals(object obj)
    {
        if (obj is Order other)
        {
            return OrderId == other.OrderId;
        }
        return false;
    }

    public override string ToString()
    {
        var details = string.Join(", ", Details);
        return $"订单号: {OrderId}, {Customer}, 总金额: {TotalAmount}, 订单明细: {details}";
    }
}

public class OrderService
{
    private List<Order> orders = new List<Order>();

    public void AddOrder(Order order)
    {
        if (orders.Contains(order))
        {
            throw new Exception("订单已存在，无法添加重复订单");
        }
        orders.Add(order);
    }

    public void DeleteOrder(string orderId)
    {
        var order = orders.FirstOrDefault(o => o.OrderId == orderId);
        if (order == null)
        {
            throw new Exception("订单不存在，无法删除");
        }
        orders.Remove(order);
    }

    public void UpdateOrder(string orderId, Order newOrder)
    {
        var existingOrder = orders.FirstOrDefault(o => o.OrderId == orderId);
        if (existingOrder == null)
        {
            throw new Exception("订单不存在，无法修改");
        }

        var index = orders.IndexOf(existingOrder);
        orders[index] = newOrder;
    }

    public List<Order> QueryOrders(Func<Order, bool> predicate)
    {
        return orders.Where(predicate).OrderByDescending(o => o.TotalAmount).ToList();
    }

    public List<Order> SortOrders(string sortBy = "OrderId", Func<Order, object> customSort = null)
    {
        if (customSort != null)
        {
            return orders.OrderBy(customSort).ToList();
        }

        switch (sortBy)
        {
            case "OrderId":
                return orders.OrderBy(o => o.OrderId).ToList();
            case "TotalAmount":
                return orders.OrderByDescending(o => o.TotalAmount).ToList();
            default:
                throw new Exception("无效的排序字段");
        }
    }

    public void AddOrderDetail(string orderId, OrderDetail orderDetail)
    {
        var order = orders.FirstOrDefault(o => o.OrderId == orderId);
        if (order == null)
        {
            throw new Exception("订单不存在，无法添加订单明细");
        }

        if (order.Details.Contains(orderDetail))
        {
            throw new Exception("订单明细已存在，无法添加重复明细");
        }

        order.Details.Add(orderDetail);
    }

    public void Export(string filePath)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
        using (StreamWriter writer = new StreamWriter(filePath))
        {
            serializer.Serialize(writer, orders);
        }
    }

    public void Import(string filePath)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
        using (StreamReader reader = new StreamReader(filePath))
        {
            List<Order> importedOrders = (List<Order>)serializer.Deserialize(reader);
            foreach (Order order in importedOrders)
            {
                if (!orders.Contains(order))
                {
                    orders.Add(order);
                }
            }
        }
    }
}
